package com.github.mpusher.offline.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

/**
 * Created by ThinkPad on 2017/9/25.
 */
public class HttpClientUtils {
    private static final String APPLICATION_JSON = "application/json";

    private static final String APPLICATION_XML = "application/xml";

    @SuppressWarnings("unused")
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    private static final String UTF_8 = "UTF-8";
    public static String sendData(String data, String url, String charset, String contentType) {
        HttpClient httpClient = getHttpClient();//new HttpClient();
        PostMethod httpPost = new PostMethod(url);
        httpPost.setRequestHeader("content-type", contentType);
        httpPost.addRequestHeader("Connection", "close");
        httpPost.setRequestBody(data);
        try {
            RequestEntity se = new StringRequestEntity(data,null,charset);
            httpPost.setRequestEntity(se);
            int responseCode = httpClient.executeMethod(httpPost);
            if (responseCode == 200) {
                byte[] resBody = httpPost.getResponseBody();
                String responseString = "";
                if (null == resBody || 0 == resBody.length) {
                    responseString = httpPost.getResponseBodyAsString();
                } else {
                    responseString = new String(resBody, UTF_8);
                }
                return responseString;
            }

        } catch (Exception e) {
            e.printStackTrace();
            // Assert.fail(e.getLocalizedMessage());
        } finally {
            httpPost.releaseConnection();
        }
        return "";
    }

    private static HttpClient getHttpClient() {
        HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = httpConnectionManager.getParams();
        params.setConnectionTimeout(5000);
        params.setSoTimeout(50000);
        params.setDefaultMaxConnectionsPerHost(32);//important
        params.setMaxTotalConnections(256);//important
        params.setBooleanParameter("http.protocol.expect-continue" , false);
        HttpClient httpClient = new HttpClient(httpConnectionManager);
        return httpClient;
    }
}
